package org.zkoss.zktc.unittest;

import groovy.lang.Binding;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.junit.Assert;
import org.junit.Before;
import org.zkoss.zktc.core.Variables;
import org.zkoss.zktc.core.groovy.Snippet;
import org.zkoss.zktc.core.junit.TestCaseBase;

public class GroovyTestCaseBase extends TestCaseBase {

	protected Binding binding;
	//	
	@Before
	public void beforeTest() {
		binding = new Binding() {
			// allow everything
			public Object getVariable(String name) {
				if ("driver".equals(name)) {
					return getDriver();
				} else if ("newDriver".equals(name)) {
					return getDriver(true);
				} else if ("testCaseUrl".equals(name)) {
					return getTestCaseUrl();
				}

				return super.getVariables().get(name);
			}
		};

		binding.setVariable(Variables.ASSERTER, new Assert(){});
	}

	protected String getGroovy() {
		// _ to running in eclipse
		return getGroovy(getClass().getSimpleName()+"_");
	}
	protected String getGroovy(String name) {
		URL url = getClass().getResource(name + ".groovy");
		if (url == null) {
			throw new RuntimeException("groovy file not found of " + name);
		}
		InputStream is = null;
		BufferedReader r = null;
		StringBuilder sb = new StringBuilder();
		try {
			r = new BufferedReader(new InputStreamReader(is = url.openStream(),
					"UTF8"));
			String l;
			while ((l = r.readLine()) != null) {
				l = l.trim();
				sb.append(l).append("\n");
			}
		} catch (Exception e) {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e1) {
				}
			}
			throw new RuntimeException(e.getMessage(), e);
		}

		return sb.toString();
	}
	
	protected List<Snippet> getSnippets() {
		String name = getClass().getSimpleName();
		URL url = getClass().getResource(name + "_.groovy");// _ to running in
															// eclipse
		if (url == null) {
			throw new RuntimeException("groovy file not found by " + name);
		}
		InputStream is = null;
		BufferedReader r = null;
		
		ArrayList<Snippet> snippets = new ArrayList<Snippet>();
		try {
			r = new BufferedReader(new InputStreamReader(is = url.openStream(),
					"UTF8"));
			String l;
			while ((l = r.readLine()) != null) {
				l = l.trim();
				snippets.add(new Snippet(l));
			}
		} catch (Exception e) {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e1) {
				}
			}
			throw new RuntimeException(e.getMessage(), e);
		}

		return snippets;
	}
}
